import DiseaseAPI from '@/api/Disease';
import { Box, FieldCols, mapField, useCall, useQueryValue, useReq } from '@/components';
import { StateProvider, useSelector } from '@/components/StateProvider';
import { companyNameField } from '@/constants/sharedFields';
import { commonRules, pathJoin } from '@/utils';
import { catchAndScrollFor } from '@/utils/fp';
import { Button, Divider, Form, message, Space, Spin } from 'antd';
import React, { useEffect, useLayoutEffect, useRef } from 'react';
import DiseaseItemEdit from './components/DiseaseItemEdit';
import DiseaseTree from './components/DiseaseTree';
import { dataToForm, formToData } from './components/shared';

const RenderForm = () => {
  const noSelection = useSelector((t) => (t?.currentKey || '0') === '0');

  return noSelection ? (
    <Box py={3} flex dir='row' jus='center' className='c-text-secondary'>
      选择左侧的节点进行编辑
    </Box>
  ) : (
    <DiseaseItemEdit />
  );
};

const TreeEditor = () => (
  <Box flex dir='row' ali='stretch' style={{ flex: '1 1 auto', overflow: 'hidden' }}>
    <Box style={{ flex: '0 0 200px' }} scroll>
      <DiseaseTree />
    </Box>

    <Divider type='vertical' style={{ height: 'auto' }} />

    <Box grow>
      <RenderForm />
    </Box>
  </Box>
);

function DiseaseEditPage({ history, location }) {
  const productCode = useQueryValue('productCode');
  const productName = useQueryValue('productName');
  const [form] = Form.useForm();
  const getXhr = useReq(DiseaseAPI.getByProductCode);
  const saveXhr = useReq(DiseaseAPI.insertOrUpdate);
  const stateRef = useRef();

  const loading = [getXhr.status, saveXhr.status].includes('loading');

  useEffect(() => {
    form.resetFields();
    stateRef.current.setState(null);
    if (productCode) getXhr.start(productCode);
  }, [productCode]);

  useLayoutEffect(() => {
    if (loading) return;
    const [formData, treeList] = dataToForm(getXhr.result?.data);
    form.setFieldsValue(formData);
    stateRef.current.setState({ treeList });
  }, [getXhr.result, loading]);

  const handleSave = useCall(async () => {
    const formData = await form.validateFields().catch(catchAndScrollFor(form));
    const { treeList = [] } = stateRef.current.getState() ?? {};
    if (!treeList.length) return message.warn('请添加节点');
    const data = formToData(formData, treeList);
    await saveXhr.start(data);
    message.success('保存成功');
    history?.replace(pathJoin(location.pathname, '../'));
  });

  const fields = useRef(
    [
      companyNameField,
      ['productCode', '险种编码', null, { required: true, readOnly: true, initialValue: productCode }],
      ['productName', '险种名称', null, { required: true, readOnly: true, initialValue: productName }],
    ].map(mapField),
  ).current;
  fields[0].readOnly = true;

  const element = (
    <>
      <Form form={form} component={false}>
        <FieldCols form={form} fields={fields} />
      </Form>

      <Divider />

      <TreeEditor />
    </>
  );

  return (
    <Box style={{ height: '100%' }} flex dir='col'>
      <StateProvider ref={stateRef}>{loading ? <Spin spinning={loading}>{element}</Spin> : element}</StateProvider>

      <Divider />

      <Box flex jus='center' py={1} className='form-page-btn'>
        <Space size='large'>
          <Button disabled={loading} onClick={history?.goBack}>
            返回
          </Button>
          <Button loading={saveXhr.status === 'loading'} type='primary' onClick={handleSave}>
            保存
          </Button>
        </Space>
      </Box>
    </Box>
  );
}

export default DiseaseEditPage;
